package com.dqyy.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dqyy.order.entity.Dish;
import com.dqyy.order.entity.Order;
import com.dqyy.order.entity.OrderDetail;
import com.dqyy.order.mapper.OrderMapper;
import com.dqyy.order.mapper.OrderDetailMapper;
import com.dqyy.order.service.DishService;
import com.dqyy.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private DishService dishService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    @Transactional
    public Long createOrder(List<Long> dishIds, List<Integer> quantities) {
        // 生成订单号
        String orderNo = UUID.randomUUID().toString().replace("-", "");
        
        // 计算订单总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (int i = 0; i < dishIds.size(); i++) {
            Dish dish = dishService.getById(dishIds.get(i));
            if (dish != null && dish.getStatus() == 1) {
                totalAmount = totalAmount.add(dish.getPrice().multiply(new BigDecimal(quantities.get(i))));
            }
        }

        // 创建订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setTotalAmount(totalAmount);
        order.setStatus(0);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        save(order);

        // 创建订单明细
        for (int i = 0; i < dishIds.size(); i++) {
            Dish dish = dishService.getById(dishIds.get(i));
            if (dish != null && dish.getStatus() == 1) {
                OrderDetail detail = new OrderDetail();
                detail.setOrderId(order.getId());
                detail.setDishId(dish.getId());
                detail.setDishName(dish.getName());
                detail.setDishPrice(dish.getPrice());
                detail.setQuantity(quantities.get(i));
                detail.setCreateTime(LocalDateTime.now());
                detail.setUpdateTime(LocalDateTime.now());
                orderDetailMapper.insert(detail);
            }
        }

        return order.getId();
    }

    @Override
    @Transactional
    public boolean payOrder(Long orderId) {
        Order order = getById(orderId);
        if (order != null && order.getStatus() == 0) {
            order.setStatus(1);
            order.setUpdateTime(LocalDateTime.now());
            return updateById(order);
        }
        return false;
    }

    @Override
    @Transactional
    public boolean cancelOrder(Long orderId) {
        Order order = getById(orderId);
        if (order != null && order.getStatus() == 0) {
            order.setStatus(2);
            order.setUpdateTime(LocalDateTime.now());
            return updateById(order);
        }
        return false;
    }

    @Override
    public Map<String, Object> getOrderSummary() {
        Map<String, Object> summary = new HashMap<>();
        
        // 获取总订单数
        long totalOrders = count();
        summary.put("totalOrders", totalOrders);
        
        // 获取总销售额
        BigDecimal totalSales = BigDecimal.ZERO;
        List<Order> paidOrders = list(new LambdaQueryWrapper<Order>().eq(Order::getStatus, 1));
        for (Order order : paidOrders) {
            totalSales = totalSales.add(order.getTotalAmount());
        }
        summary.put("totalSales", totalSales);
        
        // 获取今日订单数
        LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        long todayOrders = count(new LambdaQueryWrapper<Order>()
                .ge(Order::getCreateTime, today));
        summary.put("todayOrders", todayOrders);
        
        return summary;
    }

    @Override
    public IPage<Order> getOrderList(Page<Order> page, Integer status) {
        log.info("开始执行分页查询 - page: {}, size: {}, status: {}", 
            page.getCurrent(), page.getSize(), status);
        
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        if (status != null) {
            wrapper.eq(Order::getStatus, status);
        }
        wrapper.orderByDesc(Order::getCreateTime);
        
        // 使用 baseMapper 执行分页查询
        IPage<Order> result = baseMapper.selectPage(page, wrapper);
        
        log.info("分页查询SQL执行完成 - 总记录数: {}, 当前页记录数: {}", 
            result.getTotal(), result.getRecords().size());
        
        return result;
    }

    @Override
    public Map<String, Object> getOrderDetail(Long orderId) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取订单信息
        Order order = getById(orderId);
        result.put("order", order);
        
        if (order != null) {
            // 获取订单明细
            List<OrderDetail> details = orderDetailMapper.selectList(
                    new LambdaQueryWrapper<OrderDetail>()
                            .eq(OrderDetail::getOrderId, orderId)
            );
            result.put("details", details);
            
            // 计算订单总金额
            BigDecimal totalAmount = details.stream()
                    .map(detail -> detail.getDishPrice().multiply(new BigDecimal(detail.getQuantity())))
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            result.put("totalAmount", totalAmount);
        }
        
        return result;
    }
} 